package cn.tworice.admin.service.impl;

import cn.tworice.admin.dao.AdminDao;
import cn.tworice.admin.dao.SystemDao;
import cn.tworice.admin.service.AdminService;
import cn.tworice.admin.service.RoleService;
import cn.tworice.auth.CacheConst;
import cn.tworice.common.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminDao dao;

    @Autowired
    private SystemDao systemDao;

    @Autowired
    private RoleService roleService;

    /**
     * 获取所有管理员账号信息
     * @author 二饭
     * @email 1786705138@qq.com
     */
    @Override
    public List<Admin> getAdminList(Integer page, Integer pageSize,Admin entity) {
        return systemDao.queryAdminList(page*pageSize,pageSize,null,entity);
    }


    /**
     * 添加一个管理员账号，返回添加管理员账号后的账号信息
     * @author 二饭[tworice@sina.cn][2022/1/16 23:22]
     */
    @Override
    public String addAdmin(Admin admin) {
        String id = null;
        if(admin.getId()==null||admin.getId().isEmpty()){
            admin.setStatus(0);
            id = UUID.randomUUID().toString().replaceAll("-", "");
            admin.setId(id);
            admin.setDate(System.currentTimeMillis());
            systemDao.insertAdmin(admin);
        }else{
            systemDao.updateAdmin(admin);
            id = admin.getId();
        }
        return id;
    }

    /**
     * 删除管理员账号
     * @author 二饭
     * @email 1786705138@qq.com
     */
    @Override
    public void delAdminByIds(String[] ids) {
        systemDao.delAdmin(ids);
        // 同时删除该用户的所有角色信息
        roleService.delAdminRoleByAdmin(ids);

        CacheConst.clearResources(ids);
        CacheConst.clearRoles(ids);
    }

    /**
     * 更新管理员密码
     * @Author 二饭
     * @Email 1786705138@qq.com
     * @Date 2021/12/3 20:44
     */
    @Override
    public boolean updateAdminInfo(Admin admin) {
        int i=systemDao.updateAdminPwd(admin);
        if(i==1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Admin getInfo(String id) {
        return dao.queryInfo(id);
    }

    /**
     * 批量导入数据
     * @param list
     * @return
     */
    @Override
    public int save(List<Admin> list) {
        list.forEach(item->{
            item.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            item.setDate(System.currentTimeMillis());
        });
        return dao.insertList(list);
    }

    @Override
    public int getAdminTotal(Admin entity) {
        return systemDao.queryAdminTotal(entity);
    }


}
